#####################################
##REPLICATION FOR MCGHEE, ET AL.,####
##"A PRIMARY CAUSE OF PARTISANSHIP"##
#####################################

##Table A1 (Appendix)##

#Load Data#
library(Zelig)
library("ZeligMultilevel")
library(sandwich)
setwd("XXXX") #ENTER DIRECTORY PATHNAME IN PLACE OF XXXX

legyrd <- read.csv("legislator primaries.dem.csv", header=TRUE)
legyrr <- read.csv("legislator primaries.rep.csv", header=TRUE)

#generate election year counter#
legyrd$yrcnt <- (legyrd$elec-1992)/2
legyrr$yrcnt <- (legyrr$elec-1992)/2

#drop ideowt var, which is not used for this table#
legyrd$ideowt <- NULL
legyrr$ideowt <- NULL

#drop missing data#
legyrd <- na.omit(legyrd)
legyrr <- na.omit(legyrr)

##Multilevel model
#Democrats
z.out <- zelig(pred_np ~ semicl + semiop + open + nonpart + pvote +
	tag(1 | icpsrst) + tag(1 | yrcnt), 
	model="ls.mixed", data=legyrd)
summary(z.out)
length(legyrd$icpsrst)

#Republicans
z.out <- zelig(pred_np ~ semicl + semiop + open + nonpart + pvote +
	tag(1 | icpsrst) + tag(1 | yrcnt), 
	model="ls.mixed", data=legyrr)
summary(z.out)
length(legyrr$icpsrst)

##Multilevel model w/ year interactions
#Democrats
z.out <- zelig(pred_np ~ semicl + semiop + open + nonpart + pvote +
	yrcnt + I(yrcnt*semicl) + I(yrcnt*semiop) + I(yrcnt*open) + 
	I(yrcnt*nonpart) + tag(1 | icpsrst) + tag(1 | yrcnt), 
	model="ls.mixed", data=legyrd)
summary(z.out)
length(legyrd$icpsrst)

#Republicans
z.out <- zelig(pred_np ~ semicl + semiop + open + nonpart + pvote + 
	yrcnt + I(yrcnt*semicl) + I(yrcnt*semiop) + I(yrcnt*open) + 
	I(yrcnt*nonpart) + tag(1 | icpsrst) + tag(1 | yrcnt), 
	model="ls.mixed", data=legyrr)
summary(z.out)
length(legyrr$icpsrst)

